<?php

namespace app\admin\controller;

use think\Db;

class StreetApply extends Base
{

    /**
     * 添加申请
     */
    public function addStreetApply()
    {
        $data = [];
        input('cid') ? $data['cid'] = input('cid') : $this->err('缺少用户编码！');

        $data['createTime'] = createTime();

        $user = model('user')->where(['id' => $data['cid']])->find();
        if (!empty($user)) {
            $data['mobile'] = $user['mobile'];
            $data['name'] = $user['name'];
        } else {
            $this->err('用户编码错误！');
        }

        $res = model('streetApply')->editData($data);

        $res ? $this->suc($res) : $this->err('操作失败！');
    }

    /**
     * 获取申请列表
     */
    public function getStreetApplyList()
    {
        $where = [];

        input('name') ? $where['s.name'] = ['like', '%' . input('name') . '%'] : true;

        input('mobile') ? $where['s.mobile'] = ['like', '%' . input('mobile') . '%'] : true;

        input('city') ? $where['u.city'] = ['like',input('city') . '%'] : true;

        input('isPay') ? $isPay= input('isPay') : true;

        if(!empty($isPay)){

          if($isPay ==1){

              $where['points'] = ['<>',0.00];

          }else{

              $where['points'] = 0.00;

          }

        }

        $res = model('streetApply')
             ->alias('s')
             ->field('s.*,u.city')
             ->join('user u','u.id = s.cid','left')
             ->where($where)
             ->order('s.status asc ,s.createTime desc')
             ->paginate(10)
             ->toArray();

        if (!$res) {
            $this->err('查询错误！');
        } else {
            $rep = $res['data'];

            foreach ($rep as &$value){

                $user = model('user')->field('points')->where(['id'=>$value['cid']])->find();

                if($user['points'] !=0.00 ){

                    $value['isPay'] =1;

                }else{

                    $value['isPay'] =0;

                }

            }
            $res['data'] = $rep;
            $this->suc($res);
        }
    }

    /**
     * 审核申请
     */
    public function auditApply()
    {
        $data = [];
        input('id') ? $data['id'] = input('id') : $this->err('缺少申请主键！');
        input('status') != null ? $data['status'] = input('status') : $this->err('缺少申请状态！');

        if ($data['status'] == 2) {
            input('reason') ? $data['reason'] = input('reason') : $this->err('缺少失败原因！');
        }
        $apply = model('StreetApply')->where(['id' => $data['id']])->find();
        $apply ? true : $this->err('申请编码有误！');

        $res = model('streetApply')->editData($data, $data['id']);
        if($data['status'] == 1){ //申请通过
            $user_data = [
                'id' => $apply['cid'],
                'isPartner' => 1
            ];
            model('user')->editData($user_data, $user_data['id']);
        }

        $res ? $this->suc($res) : $this->err('操作失败！');
    }

}
